// 键盘响应HOOK
import { useState, useEffect } from 'react'

const useKeyPress = (targetKeyCode) => {
  // 检测按键有没有被按到
  const [keyPress, setKeyPress] = useState(false)

  // 键盘按键按下事件
  const keyDownHandler = ({ keyCode }) => {
    if (keyCode === targetKeyCode) {
      setKeyPress(true)
    }
  }

  // 键盘按键弹起事件
  const keyUpHandler = ({ keyCode }) => {
    if (keyCode === targetKeyCode) {
      setKeyPress(false)
    }
  }

  useEffect(() => {
    document.addEventListener('keydown', keyDownHandler)
    document.addEventListener('keyup', keyUpHandler)
    return () => {
      document.removeEventListener('keydown', keyDownHandler)
      document.removeEventListener('keyup', keyUpHandler)
    }
  }, [])

  return keyPress
}

export default useKeyPress